package com.bf.electroplating.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bf.electroplating.login.UserContext;
import com.bf.electroplating.pojo.entity.*;
import com.bf.electroplating.pojo.vo.enterprise.*;
import com.bf.electroplating.pojo.vo.home.EnterpriseDetailVO;
import com.bf.electroplating.pojo.vo.sewageWarningConfig.SewageWarningVO;
import com.bf.electroplating.service.*;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前端企业级环保管理驾驶舱数据服务实现类
 */
@Slf4j
@Service
public class FrontEnterpriseServiceImpl implements IFrontEnterpriseService {

    @Autowired
    private ComCompanyService comCompanyService;

    @Autowired
    private ComEnvironmentallyFacilityService comEnvironmentallyFacilityService;

    @Autowired
    private IWasteGasMonitoringService wasteGasMonitoringService;

    @Autowired
    private IRainfallOutletMonitoringService rainfallOutletMonitoringService;
    @Autowired
    private PubParamDictionaryService pubParamDictionaryService;
    @Resource
    private ISewageWarningConfigService sewageWarningConfigService;
    @Resource
    private IEnterpriseOutfallValveService enterpriseOutfallValveService;
    
    @Resource
    private IInflowManagementService inflowManagementService;
    
    @Resource
    private IRainfallOutletWeatherDataService rainfallOutletWeatherDataService;
    
    @Resource
    private ComContingencySpaceFacilityService comContingencySpaceFacilityService;


    @Override
    public RainwaterMonitoringDataVO getRainwaterMonitoringData() {
        RainwaterMonitoringDataVO data = new RainwaterMonitoringDataVO();
        
        // 闸阀状态
        data.setValveStatus("开");
        data.setValveStatusColor("green");
        
        // 监测数据
        MonitoringDataVO monitoringData = new MonitoringDataVO();
        monitoringData.setPhValue(15 + new Random().nextInt(10));
        monitoringData.setConductivity(10 + new Random().nextInt(10));
        monitoringData.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        data.setMonitoringData(monitoringData);
        
        return data;
    }

    @Override
    public PowerManagementDataVO getPowerManagementData() {
        PowerManagementDataVO data = new PowerManagementDataVO();
        
        // 环保设备用电数据
        List<DeviceVO> environmentalDevices = new ArrayList<>();
        for (int i = 1; i <= 2; i++) {
            DeviceVO device = new DeviceVO();
            device.setDeviceName("环保设备" + (char)('A' + i - 1));
            device.setVoltage((20 + new Random().nextInt(5)) + "V");
            device.setCurrent((20 + new Random().nextInt(5)) + "A");
            device.setTemperature((35 + new Random().nextInt(5)) + "°C");
            environmentalDevices.add(device);
        }
        
        // 生产设备用电数据
        List<DeviceVO> productionDevices = new ArrayList<>();
        DeviceVO prodDevice = new DeviceVO();
        prodDevice.setDeviceName("生产设备A");
        prodDevice.setVoltage((22 + new Random().nextInt(5)) + "V");
        prodDevice.setCurrent((23 + new Random().nextInt(5)) + "A");
        prodDevice.setTemperature((37 + new Random().nextInt(5)) + "°C");
        productionDevices.add(prodDevice);
        
        data.setEnvironmentalDevices(environmentalDevices);
        data.setProductionDevices(productionDevices);
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        return data;
    }

    @Override
    public EmergencySuppliesDataVO getEmergencySuppliesData() {
        EmergencySuppliesDataVO data = new EmergencySuppliesDataVO();
        
        List<SupplyVO> supplies = new ArrayList<>();
        
        String[] materialNames = {"防护服", "防毒面具", "应急药品", "消防器材", "应急照明"};
        for (String materialName : materialNames) {
            SupplyVO supply = new SupplyVO();
            supply.setMaterialName(materialName);
            supply.setQuantity(10 + new Random().nextInt(20));
            supply.setUpdateTime("2025年3月12日");
            supplies.add(supply);
        }
        
        data.setSupplies(supplies);
        data.setTotalCount(supplies.size());
        
        return data;
    }

    @Override
    public EquipmentStatisticsDataVO getEquipmentStatistics() {
        EquipmentStatisticsDataVO data = new EquipmentStatisticsDataVO();
        
        // 从环境设施表获取设备数量
        long totalEquipment = comEnvironmentallyFacilityService.count();
        long onlineEquipment = (long) (totalEquipment * 0.98); // 假设98%在线
        long offlineEquipment = totalEquipment - onlineEquipment;
        
        data.setTotalEquipment((int) totalEquipment);
        data.setOnlineEquipment((int) onlineEquipment);
        data.setOfflineEquipment((int) offlineEquipment);
        
        // 计算在线率
        double onlineRate = totalEquipment > 0 ? (double) onlineEquipment / totalEquipment * 100 : 0;
        data.setOnlineRate(Math.round(onlineRate * 100.0) / 100.0);
        
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public AlarmHandlingDataVO getAlarmHandlingData() {
        AlarmHandlingDataVO data = new AlarmHandlingDataVO();
        
        // 预警统计 - 模拟数据
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalAlarms", 700 + new Random().nextInt(100));
        statistics.put("handledAlarms", 100 + new Random().nextInt(50));
        statistics.put("unhandledAlarms", 600 + new Random().nextInt(100));
        data.setStatistics(statistics);
        
        // 预警详细列表
        List<AlarmVO> alarmList = new ArrayList<>();
        String[] alarmTypes = {"PH值异常", "流量异常", "电导率异常", "温度异常"};
        String[] deviceNames = {"监测设备A", "监测设备B", "监测设备C", "监测设备D"};
        String[] statuses = {"已处置", "未处置"};
        String[] colors = {"green", "red"};
        
        for (int i = 0; i < 2; i++) {
            AlarmVO alarm = new AlarmVO();
            alarm.setAlarmType(alarmTypes[new Random().nextInt(alarmTypes.length)]);
            alarm.setDeviceName(deviceNames[new Random().nextInt(deviceNames.length)]);
            alarm.setAlarmValue(1 + new Random().nextInt(5));
            alarm.setAlarmThreshold(2 + new Random().nextInt(3));
            alarm.setHandlingStatus(statuses[new Random().nextInt(statuses.length)]);
            alarm.setStatusColor(colors[new Random().nextInt(colors.length)]);
            alarmList.add(alarm);
        }
        
        data.setAlarmList(alarmList);
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public WasteGasTreatmentDataVO getWasteGasTreatmentData() {
        WasteGasTreatmentDataVO data = new WasteGasTreatmentDataVO();
        
        // 12个月的趋势数据
        List<String> months = Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月", 
                                          "7月", "8月", "9月", "10月", "11月", "12月");
        
        // PH值数据
        List<Integer> phValues = new ArrayList<>();
        // ORP数据
        List<Integer> orpValues = new ArrayList<>();
        
        for (int i = 0; i < 12; i++) {
            phValues.add(40 + new Random().nextInt(40));
            orpValues.add(30 + new Random().nextInt(40));
        }
        
        data.setMonths(months);
        data.setPhValues(phValues);
        data.setOrpValues(orpValues);
        data.setUnit("%");
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public HazardousWasteManagementDataVO getHazardousWasteManagementData() {
        HazardousWasteManagementDataVO data = new HazardousWasteManagementDataVO();
        
        // 当前数据
        Map<String, Object> currentData = new HashMap<>();
        int generatedQuantity = 1500 + new Random().nextInt(200);
        currentData.put("generatedQuantity", generatedQuantity);
        currentData.put("disposedQuantity", generatedQuantity - new Random().nextInt(100));
        data.setCurrentData(currentData);
        
        // 12个月的趋势数据
        List<String> months = Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月", 
                                          "7月", "8月", "9月", "10月", "11月", "12月");
        
        // 产生量和处置量数据
        List<Integer> productionData = new ArrayList<>();
        List<Integer> disposalData = new ArrayList<>();
        
        for (int i = 0; i < 12; i++) {
            productionData.add(80 + new Random().nextInt(20));
            disposalData.add(75 + new Random().nextInt(20));
        }
        
        data.setMonths(months);
        data.setProductionData(productionData);
        data.setDisposalData(disposalData);
        data.setUnit("%");
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public EmergencySpaceDataVO getEmergencySpaceData() {
        log.info("开始获取应急空间数据");
        
        EmergencySpaceDataVO data = new EmergencySpaceDataVO();
        
        try {
            // 获取所有应急空间设施数据
            List<ComContingencySpaceFacility> facilities = comContingencySpaceFacilityService.list();
            
            // 应急池数据
            PoolDataVO emergencyPool = new PoolDataVO();
            // 初雨池数据
            PoolDataVO initialRainPool = new PoolDataVO();
            
            // 查找应急池和初雨池数据
            ComContingencySpaceFacility emergencyPoolFacility = null;
            ComContingencySpaceFacility initialRainPoolFacility = null;
            
            for (ComContingencySpaceFacility facility : facilities) {
                if ("应急池".equals(facility.getType())) {
                    emergencyPoolFacility = facility;
                } else if ("初雨池".equals(facility.getType())) {
                    initialRainPoolFacility = facility;
                }
            }
            
            // 处理应急池数据
            if (emergencyPoolFacility != null) {
                emergencyPool.setCapacity(emergencyPoolFacility.getVolume());
                // 计算当前液位和容量百分比
                calculatePoolData(emergencyPool, emergencyPoolFacility, "应急池");
            } else {
                // 默认数据
                emergencyPool.setCapacity("0");
                emergencyPool.setAvailableCapacity("0");
                emergencyPool.setCurrentLevelRatio(0);
                emergencyPool.setLiquidLevel(0);
            }
            
            // 处理初雨池数据
            if (initialRainPoolFacility != null) {
                initialRainPool.setCapacity(initialRainPoolFacility.getVolume());
                // 计算当前液位和容量百分比
                calculatePoolData(initialRainPool, initialRainPoolFacility, "初雨池");
            } else {
                // 默认数据
                initialRainPool.setCapacity("0");
                initialRainPool.setAvailableCapacity("0");
                initialRainPool.setCurrentLevelRatio(0);
                initialRainPool.setLiquidLevel(0);
            }
            
            data.setEmergencyPool(emergencyPool);
            data.setInitialRainPool(initialRainPool);
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            log.info("成功获取应急空间数据");
            
        } catch (Exception e) {
            log.error("获取应急空间数据失败", e);
            // 返回默认数据
            PoolDataVO emergencyPool = new PoolDataVO();
            emergencyPool.setCapacity("131");
            emergencyPool.setAvailableCapacity("31");
            emergencyPool.setCurrentLevelRatio(60);
            emergencyPool.setLiquidLevel(60);
            
            PoolDataVO initialRainPool = new PoolDataVO();
            initialRainPool.setCapacity("200");
            initialRainPool.setAvailableCapacity("80");
            initialRainPool.setCurrentLevelRatio(35);
            initialRainPool.setLiquidLevel(35);
            
            data.setEmergencyPool(emergencyPool);
            data.setInitialRainPool(initialRainPool);
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        return data;
    }

    /**
     * 计算池子的液位和容量百分比
     */
    private void calculatePoolData(PoolDataVO poolData, ComContingencySpaceFacility facility, String poolType) {
        try {
            // 获取设施的高度
            String heightStr = facility.getHeight();
            if (heightStr == null || heightStr.trim().isEmpty()) {
                log.warn("{}设施高度为空，使用默认值", poolType);
                poolData.setAvailableCapacity("0");
                poolData.setCurrentLevelRatio(0);
                poolData.setLiquidLevel(0);
                return;
            }
            
            double height = Double.parseDouble(heightStr);
            
            // 查询该企业最新的液位数据
            LambdaQueryWrapper<RainfallOutletMonitoring> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RainfallOutletMonitoring::getCompanyId, facility.getCompanyId());
            
            // 根据池子类型查询对应的液位字段
            if ("应急池".equals(poolType)) {
                queryWrapper.isNotNull(RainfallOutletMonitoring::getEmergencyPoolLevel);
            } else if ("初雨池".equals(poolType)) {
                queryWrapper.isNotNull(RainfallOutletMonitoring::getRainOutletLevel);
            }
            
            queryWrapper.orderByDesc(RainfallOutletMonitoring::getMonitoringTime);
            queryWrapper.last("LIMIT 1");
            
            RainfallOutletMonitoring latestMonitoring = rainfallOutletMonitoringService.getOne(queryWrapper, false);
            
            if (latestMonitoring != null) {
                BigDecimal currentLevel = null;
                if ("应急池".equals(poolType)) {
                    currentLevel = latestMonitoring.getEmergencyPoolLevel();
                } else if ("初雨池".equals(poolType)) {
                    currentLevel = latestMonitoring.getRainOutletLevel();
                }
                
                if (currentLevel != null) {
                    // 计算当前液位百分比
                    double levelRatio = (currentLevel.doubleValue() / height) * 100;
                    int levelRatioInt = (int) Math.round(levelRatio);
                    
                    // 确保百分比在0-100之间
                    levelRatioInt = Math.max(0, Math.min(100, levelRatioInt));
                    
                    poolData.setCurrentLevelRatio(levelRatioInt);
                    poolData.setLiquidLevel(levelRatioInt);
                    
                    // 计算可用容量（总容量 - 当前液位）
                    String volumeStr = facility.getVolume();
                    if (volumeStr != null && !volumeStr.trim().isEmpty()) {
                        try {
                            double totalVolume = Double.parseDouble(volumeStr);
                            double usedVolume = totalVolume * (levelRatioInt / 100.0);
                            double availableVolume = totalVolume - usedVolume;
                            poolData.setAvailableCapacity(String.format("%.1f", availableVolume));
                        } catch (NumberFormatException e) {
                            log.warn("{}容积数据格式错误: {}", poolType, volumeStr);
                            poolData.setAvailableCapacity("0");
                        }
                    } else {
                        poolData.setAvailableCapacity("0");
                    }
                    
                    log.info("{}当前液位: {}, 高度: {}, 液位百分比: {}%", 
                            poolType, currentLevel, height, levelRatioInt);
                } else {
                    log.warn("{}液位数据为空", poolType);
                    poolData.setAvailableCapacity("0");
                    poolData.setCurrentLevelRatio(0);
                    poolData.setLiquidLevel(0);
                }
            } else {
                log.warn("未找到{}的液位数据", poolType);
                poolData.setAvailableCapacity("0");
                poolData.setCurrentLevelRatio(0);
                poolData.setLiquidLevel(0);
            }
            
        } catch (Exception e) {
            log.error("计算{}数据失败", poolType, e);
            poolData.setAvailableCapacity("0");
            poolData.setCurrentLevelRatio(0);
            poolData.setLiquidLevel(0);
        }
    }

    @Override
    public ParkEnterpriseInfoDataVO getParkEnterpriseInfoData() {
        ParkEnterpriseInfoDataVO data = new ParkEnterpriseInfoDataVO();
        
        // 企业基本信息 - 从企业表获取第一个企业作为示例
        List<ComCompany> companies = comCompanyService.list();
        EnterpriseInfoVO enterpriseInfo = new EnterpriseInfoVO();
        
        if (!companies.isEmpty()) {
            ComCompany company = companies.get(0);
            enterpriseInfo.setCompanyName(company.getCompanyName());
            enterpriseInfo.setContactPerson(company.getEnvironmentalOfficer());
            enterpriseInfo.setContactPhone(company.getEnvironmentalOfficerPhone());
            enterpriseInfo.setPlatingType("镀锌");
            enterpriseInfo.setProductionLineCount(3 + new Random().nextInt(5));
            enterpriseInfo.setWorkshopCount(2 + new Random().nextInt(3));
            enterpriseInfo.setCodeType("A001");
            enterpriseInfo.setWorkshopInfo("这里是车间信息");
        } else {
            // 默认数据
            enterpriseInfo.setCompanyName("碧水环保科技有限公司");
            enterpriseInfo.setContactPerson("赵小军");
            enterpriseInfo.setContactPhone("15246768977");
            enterpriseInfo.setPlatingType("镀锌");
            enterpriseInfo.setProductionLineCount(5);
            enterpriseInfo.setWorkshopCount(3);
            enterpriseInfo.setCodeType("A001");
            enterpriseInfo.setWorkshopInfo("这里是车间信息");
        }
        
        data.setEnterpriseInfo(enterpriseInfo);
        
        // 地图相关数据
        Map<String, Object> mapData = new HashMap<>();
        mapData.put("longitude", 119.8);
        mapData.put("latitude", 28.9);
        mapData.put("zoomLevel", 15);
        data.setMapData(mapData);
        
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public WasteGasMonitoringListVO getWasteGasMonitoringList(String companyId) {
        log.info("开始获取废气处理设施水质检测列表数据");
        
        WasteGasMonitoringListVO data = new WasteGasMonitoringListVO();
        
        try {
            LambdaQueryWrapper<WasteGasMonitoring> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(companyId)) {
                lambdaQueryWrapper.eq(WasteGasMonitoring::getCompanyId, companyId);
            }
            // 获取所有废气监测数据
            List<WasteGasMonitoring> allMonitoringData = wasteGasMonitoringService.list(lambdaQueryWrapper);
            // 按设备名称和MN码分组，合并同一设备的多个检测因子
            Map<String, List<WasteGasMonitoring>> groupedByDevice = allMonitoringData.stream()
                    .collect(Collectors.groupingBy(monitoring -> 
                        monitoring.getDeviceName() + "_" + monitoring.getMnCode()));
            List<WasteGasMonitoringListVO.WasteGasMonitoringDeviceVO> deviceList = new ArrayList<>();
            int totalDevices = 0;
            int onlineDevices = 0;
            int offlineDevices = 0;
            for (Map.Entry<String, List<WasteGasMonitoring>> entry : groupedByDevice.entrySet()) {
                List<WasteGasMonitoring> deviceMonitoringList = entry.getValue();
                if (deviceMonitoringList.isEmpty()) continue;
                WasteGasMonitoring firstMonitoring = deviceMonitoringList.get(0);
                WasteGasMonitoringListVO.WasteGasMonitoringDeviceVO deviceVO = 
                    new WasteGasMonitoringListVO.WasteGasMonitoringDeviceVO();
                // 基本信息
                deviceVO.setDeviceName(firstMonitoring.getDeviceName());
                deviceVO.setMnCode(firstMonitoring.getMnCode());
                deviceVO.setCompanyName(firstMonitoring.getCompanyName());
                deviceVO.setCompanyId(firstMonitoring.getCompanyId());
                
                // 合并监测因子
                String monitoringFactors = deviceMonitoringList.stream()
                        .map(WasteGasMonitoring::getMonitoringFactor)
                        .distinct()
                        .collect(Collectors.joining("、"));
                deviceVO.setMonitoringFactor(monitoringFactors);
                
                // 获取最新的PH和ORP值
                WasteGasMonitoring latestMonitoring = deviceMonitoringList.stream()
                        .filter(m -> m.getMonitoringTime() != null)
                        .max(Comparator.comparing(WasteGasMonitoring::getMonitoringTime))
                        .orElse(firstMonitoring);
                
                deviceVO.setPhValue(latestMonitoring.getPhValue());
                deviceVO.setOrpValue(latestMonitoring.getOrpValue());
                if (deviceVO.getPhValue()==null&&deviceMonitoringList.size()>1){
                    deviceVO.setPhValue(deviceMonitoringList.get(1).getPhValue());
                }
                if (deviceVO.getOrpValue()==null&&deviceMonitoringList.size()>1){
                    deviceVO.setOrpValue(deviceMonitoringList.get(1).getOrpValue());
                }
                deviceVO.setStatus(latestMonitoring.getStatus());
                
                // 设置状态颜色
                if ("在线".equals(latestMonitoring.getStatus())) {
                    deviceVO.setStatusColor("green");
                    onlineDevices++;
                } else {
                    deviceVO.setStatusColor("red");
                    offlineDevices++;
                }
                
                // 格式化监测时间
                if (latestMonitoring.getMonitoringTime() != null) {
                    deviceVO.setMonitoringTime(latestMonitoring.getMonitoringTime()
                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                } else {
                    deviceVO.setMonitoringTime("--");
                }
                
                deviceList.add(deviceVO);
                totalDevices++;
            }
            
            // 按设备名称排序
            deviceList.sort(Comparator.comparing(WasteGasMonitoringListVO.WasteGasMonitoringDeviceVO::getDeviceName));
            
            data.setDeviceList(deviceList);
            data.setTotalDevices(totalDevices);
            data.setOnlineDevices(onlineDevices);
            data.setOfflineDevices(offlineDevices);
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            log.info("成功获取废气处理设施水质检测列表，共{}个设备，在线{}个，离线{}个", 
                    totalDevices, onlineDevices, offlineDevices);
            
        } catch (Exception e) {
            log.error("获取废气处理设施水质检测列表数据失败", e);
            // 返回空数据
            data.setDeviceList(new ArrayList<>());
            data.setTotalDevices(0);
            data.setOnlineDevices(0);
            data.setOfflineDevices(0);
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        return data;
    }

    @Override
    public RainfallOutletChartVO getRainfallOutletChart(String companyId) {
        log.info("开始获取雨排口折线图数据");
        
        RainfallOutletChartVO data = new RainfallOutletChartVO();
        
        try {
            // 获取最近5天的雨排口监控数据
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusDays(5);
            
            LambdaQueryWrapper<RainfallOutletMonitoring> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(companyId)) {
                queryWrapper.eq(RainfallOutletMonitoring::getCompanyId, companyId);
            }
            queryWrapper.orderByAsc(RainfallOutletMonitoring::getMonitoringTime);
            
            List<RainfallOutletMonitoring> monitoringDataList = rainfallOutletMonitoringService.list(queryWrapper);
            
            // 构建闸阀状态信息
            RainfallOutletChartVO.ValveStatusVO valveStatus = new RainfallOutletChartVO.ValveStatusVO();
            if (!monitoringDataList.isEmpty()&&monitoringDataList.stream().filter(i->"应急池阀门".equals(i.getDeviceName())).count()>0) {
                // 获取最新的闸阀状态
                RainfallOutletMonitoring latestData = monitoringDataList.stream().filter(i->"应急池阀门".equals(i.getDeviceName())).collect(Collectors.toList()).get(0);
                String valveStatusValue = latestData.getRainOutletValveStatus();
                valveStatus.setStatus("0".equals(valveStatusValue) ? "关" : "开");
                valveStatus.setStatusColor("0".equals(valveStatusValue) ? "green" : "red");
                valveStatus.setValveType("手自一体闸阀");
                data.setNeedShowEmergency("1");
            } else {
                // 默认状态
                valveStatus.setStatus("关");
                valveStatus.setStatusColor("red");
                valveStatus.setValveType("应急池阀门");
                data.setNeedShowEmergency("0");
            }
            RainfallOutletChartVO.ValveStatusVO rainStatusVO = new RainfallOutletChartVO.ValveStatusVO();
            if (!monitoringDataList.isEmpty()&&monitoringDataList.stream().filter(i->"雨排口阀门".equals(i.getDeviceName())).count()>0) {
                // 获取最新的闸阀状态
                RainfallOutletMonitoring latestData = monitoringDataList.stream().filter(i->"雨排口阀门".equals(i.getDeviceName())).collect(Collectors.toList()).get(0);
                String valveStatusValue = latestData.getRainOutletValveStatus();
                rainStatusVO.setStatus("0".equals(valveStatusValue) ? "关" : "开");
                rainStatusVO.setStatusColor("0".equals(valveStatusValue) ? "green" : "red");
                rainStatusVO.setValveType("雨排口阀门");
            } else {
                // 默认状态
                rainStatusVO.setStatus("关");
                rainStatusVO.setStatusColor("red");
                rainStatusVO.setValveType("雨排口阀门");
            }
            data.setRainValveStatus(rainStatusVO);
            // 构建图表数据
            RainfallOutletChartVO.ChartDataVO chartData = new RainfallOutletChartVO.ChartDataVO();
            
            // 不再需要按日期分组，直接使用RainfallOutletWeatherData表的数据
            
            // 构建时间轴标签（最近5天）
            List<String> timeLabels = new ArrayList<>();
            for (int i = 4; i >= 0; i--) {
                String date = LocalDateTime.now().minusDays(i).format(DateTimeFormatter.ofPattern("MM-dd"));
                timeLabels.add(date);
            }
            
            // 获取所有企业的extraSiteId
            List<ComCompany> companies = comCompanyService.list();
            List<Integer> extraSiteIds = companies.stream()
                    .filter(company -> company.getExtraSiteId() != null)
                    .map(ComCompany::getExtraSiteId)
                    .distinct()
                    .collect(Collectors.toList());
            
            log.info("找到 {} 个企业的外部站点ID: {}", extraSiteIds.size(), extraSiteIds);
            
            // 构建降雨量数据系列（基于RainfallOutletWeatherData表）
            RainfallOutletChartVO.DataSeriesVO rainfallSeries = new RainfallOutletChartVO.DataSeriesVO();
            rainfallSeries.setName("降雨量");
            rainfallSeries.setUnit("mm");
            rainfallSeries.setColor("#1890ff");
            rainfallSeries.setIcon("◎");
            
            List<BigDecimal> rainfallData = new ArrayList<>();
            
            // 构建电导率数据系列（基于RainfallOutletWeatherData表）
            RainfallOutletChartVO.DataSeriesVO conductivitySeries = new RainfallOutletChartVO.DataSeriesVO();
            conductivitySeries.setName("电导率");
            conductivitySeries.setUnit("μS/cm");
            conductivitySeries.setColor("#faad14");
            conductivitySeries.setIcon("●");
            
            List<BigDecimal> conductivityData = new ArrayList<>();
            
            // 按日期获取数据
            for (int i = 4; i >= 0; i--) {
                LocalDate currentDate = LocalDate.now().minusDays(i);
                LocalDateTime startOfDay = currentDate.atStartOfDay();
                LocalDateTime endOfDay = currentDate.plusDays(1).atStartOfDay();
                
                // 查询RainfallOutletWeatherData表获取降雨量和电导率数据
                LambdaQueryWrapper<RainfallOutletWeatherData> weatherQueryWrapper = new LambdaQueryWrapper<>();
                if (!extraSiteIds.isEmpty()) {
                    weatherQueryWrapper.in(RainfallOutletWeatherData::getSiteId, extraSiteIds);
                }
                weatherQueryWrapper.between(RainfallOutletWeatherData::getDataTime, startOfDay, endOfDay);
                weatherQueryWrapper.eq(RainfallOutletWeatherData::getIsValid, true);
                weatherQueryWrapper.orderByAsc(RainfallOutletWeatherData::getDataTime);
                
                List<RainfallOutletWeatherData> weatherDataList = rainfallOutletWeatherDataService.list(weatherQueryWrapper);
                
                if (!weatherDataList.isEmpty()) {
                    // 计算当天降雨量的平均值，保留2位小数
                    double avgRainfall = weatherDataList.stream()
                            .filter(d -> d.getRainAmount() != null)
                            .mapToDouble(d -> d.getRainAmount().doubleValue())
                            .average()
                            .orElse(0.0);
                    rainfallData.add(BigDecimal.valueOf(avgRainfall).setScale(2, RoundingMode.HALF_UP));
                    
                    // 计算当天电导率的平均值（使用factorValue字段），保留2位小数
                    double avgConductivity = weatherDataList.stream()
                            .filter(d -> d.getFactorValue() != null)
                            .mapToDouble(d -> d.getFactorValue().doubleValue())
                            .average()
                            .orElse(0.0);
                    conductivityData.add(BigDecimal.valueOf(avgConductivity).setScale(2, RoundingMode.HALF_UP));
                } else {
                    // 无数据时置为0
                    rainfallData.add(BigDecimal.ZERO);
                    conductivityData.add(BigDecimal.ZERO);
                }
            }
            
            rainfallSeries.setData(rainfallData);
            conductivitySeries.setData(conductivityData);
            
            chartData.setTimeLabels(timeLabels);
            chartData.setPhSeries(rainfallSeries); // 使用降雨量数据替代PH值
            chartData.setConductivitySeries(conductivitySeries);
            
            data.setValveStatus(valveStatus);
            data.setChartData(chartData);
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
            
            log.info("成功获取雨排口折线图数据，共{}条监控记录，{}个外部站点，时间范围：{} 到 {}", 
                    monitoringDataList.size(), extraSiteIds.size(), startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), 
                    endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            
        } catch (Exception e) {
            log.error("获取雨排口折线图数据失败", e);
        }
        return data;
    }

    @Override
    public EnterpriseWastewaterChartVO getEnterpriseWastewaterChart(String waterType, String companyId) {
        log.info("开始获取企业废水折线图数据，waterType: {}, companyId: {}", waterType, companyId);
        
        EnterpriseWastewaterChartVO data = new EnterpriseWastewaterChartVO();
        
        try {
            // 构建废水类型选择配置
            EnterpriseWastewaterChartVO.WastewaterTypeConfigVO typeConfig = 
                new EnterpriseWastewaterChartVO.WastewaterTypeConfigVO();
            
            // 主要分类选项
            List<EnterpriseWastewaterChartVO.CategoryOptionVO> mainCategories = new ArrayList<>();
            
            EnterpriseWastewaterChartVO.CategoryOptionVO enterpriseWastewater = 
                new EnterpriseWastewaterChartVO.CategoryOptionVO();
            enterpriseWastewater.setName("企业废水");
            enterpriseWastewater.setValue("enterprise");
            enterpriseWastewater.setSelected(true); // 默认选中企业废水
            
            EnterpriseWastewaterChartVO.CategoryOptionVO preDischarge = 
                new EnterpriseWastewaterChartVO.CategoryOptionVO();
            preDischarge.setName("预排口");
            preDischarge.setValue("pre_discharge");
            preDischarge.setSelected(false);
            
            mainCategories.add(enterpriseWastewater);
            mainCategories.add(preDischarge);
            
            // 具体废水类型选项
            List<EnterpriseWastewaterChartVO.TypeOptionVO> wastewaterTypes = new ArrayList<>();
            
            String[] typeNames = {"含铬废水", "含镍废水", "含铜废水", "含氰废水", "酸碱废水", 
                                "其他废水", "前期处理废水", "化学镍废水"};
            if (!StringUtils.isEmpty(waterType)) {
                String waterName=pubParamDictionaryService.getNameByModuleAndCode("FSLX",waterType);
                typeNames= Arrays.asList(typeNames).stream().filter(i->i.equals(waterName)).toList().toArray(new String[0]);
            }
            for (int i = 0; i < typeNames.length; i++) {
                EnterpriseWastewaterChartVO.TypeOptionVO typeOption = 
                    new EnterpriseWastewaterChartVO.TypeOptionVO();
                typeOption.setName(typeNames[i]);
                typeOption.setValue("type_" + i);
                typeOption.setSelected(i == 0); // 默认选中含铬废水
                wastewaterTypes.add(typeOption);
            }
            
            typeConfig.setMainCategories(mainCategories);
            typeConfig.setWastewaterTypes(wastewaterTypes);
            
            // 构建污染物浓度趋势图表数据
            EnterpriseWastewaterChartVO.PollutantChartDataVO chartData = 
                new EnterpriseWastewaterChartVO.PollutantChartDataVO();
            
            // 构建时间轴标签（最近18天）
            List<String> timeLabels = new ArrayList<>();
            LocalDate startDate = LocalDate.now().minusDays(17);
            for (int i = 0; i < 18; i++) {
                LocalDate date = startDate.plusDays(i);
                timeLabels.add(date.format(DateTimeFormatter.ofPattern("MM-dd")));
            }
            
            // 从 InflowManagement 表获取真实数据
            LambdaQueryWrapper<InflowManagement> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(companyId)) {
                queryWrapper.eq(InflowManagement::getCompanyId, companyId);
            }
            if (!StringUtils.isEmpty(waterType)) {
                queryWrapper.eq(InflowManagement::getWasteWaterType, waterType);
            }
            queryWrapper.ge(InflowManagement::getDetectionDate, startDate);
            queryWrapper.le(InflowManagement::getDetectionDate, LocalDate.now());
            queryWrapper.orderByAsc(InflowManagement::getDetectionDate);
            
            List<InflowManagement> inflowDataList = inflowManagementService.list(queryWrapper);
            log.info("查询到 {} 条进水管理数据", inflowDataList.size());
            
            // 构建污染物数据系列
            List<EnterpriseWastewaterChartVO.PollutantSeriesVO> pollutantSeries = new ArrayList<>();
            
            // 六价铬数据系列（蓝色）
            EnterpriseWastewaterChartVO.PollutantSeriesVO hexavalentChromium = 
                new EnterpriseWastewaterChartVO.PollutantSeriesVO();
            hexavalentChromium.setName("六价铬");
            hexavalentChromium.setColor("#1890ff");
            hexavalentChromium.setIcon("●");
            
            // 总镍数据系列（黄色）
            EnterpriseWastewaterChartVO.PollutantSeriesVO totalNickel = 
                new EnterpriseWastewaterChartVO.PollutantSeriesVO();
            totalNickel.setName("总镍");
            totalNickel.setColor("#faad14");
            totalNickel.setIcon("●");
            
            // 总铬数据系列（红色）
            EnterpriseWastewaterChartVO.PollutantSeriesVO totalChromium = 
                new EnterpriseWastewaterChartVO.PollutantSeriesVO();
            totalChromium.setName("总铬");
            totalChromium.setColor("#f5222d");
            totalChromium.setIcon("●");
            
            // 构建数据映射，按日期分组
            Map<LocalDate, InflowManagement> dataMap = inflowDataList.stream()
                .collect(Collectors.toMap(
                    InflowManagement::getDetectionDate,
                    item -> item,
                    (existing, replacement) -> replacement // 如果有重复日期，保留最后一个
                ));
            
            // 生成18天的数据
            List<BigDecimal> hexavalentChromiumData = new ArrayList<>();
            List<BigDecimal> totalNickelData = new ArrayList<>();
            List<BigDecimal> totalChromiumData = new ArrayList<>();
            
            for (int i = 0; i < 18; i++) {
                LocalDate currentDate = startDate.plusDays(i);
                InflowManagement dayData = dataMap.get(currentDate);
                
                if (dayData != null) {
                    // 有数据的情况
                    hexavalentChromiumData.add(dayData.getHexavalentChromiumValue() != null ? 
                        dayData.getHexavalentChromiumValue() : BigDecimal.ZERO);
                    totalNickelData.add(dayData.getTotalNickelValue() != null ? 
                        dayData.getTotalNickelValue() : BigDecimal.ZERO);
                    totalChromiumData.add(dayData.getTotalChromiumValue() != null ? 
                        dayData.getTotalChromiumValue() : BigDecimal.ZERO);
                } else {
                    // 无数据的情况，置为0
                    hexavalentChromiumData.add(BigDecimal.ZERO);
                    totalNickelData.add(BigDecimal.ZERO);
                    totalChromiumData.add(BigDecimal.ZERO);
                }
            }
            
            hexavalentChromium.setData(hexavalentChromiumData);
            totalNickel.setData(totalNickelData);
            totalChromium.setData(totalChromiumData);
            
            pollutantSeries.add(hexavalentChromium);
            pollutantSeries.add(totalNickel);
            pollutantSeries.add(totalChromium);
            
            chartData.setTimeLabels(timeLabels);
            chartData.setPollutantSeries(pollutantSeries);
            chartData.setYAxisUnit("mg/L");
            chartData.setYAxisMax(100);
            
            data.setTypeConfig(typeConfig);
            data.setChartData(chartData);
            data.setCurrentDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            log.info("成功获取企业废水折线图数据，包含{}个污染物指标，时间范围：{} 到 {}，数据来源：InflowManagement表", 
                    pollutantSeries.size(), timeLabels.get(0), timeLabels.get(timeLabels.size() - 1));
            
        } catch (Exception e) {
            log.error("获取企业废水折线图数据失败", e);
            // 返回默认数据
            EnterpriseWastewaterChartVO.WastewaterTypeConfigVO typeConfig = 
                new EnterpriseWastewaterChartVO.WastewaterTypeConfigVO();
            
            // 默认主要分类
            List<EnterpriseWastewaterChartVO.CategoryOptionVO> mainCategories = new ArrayList<>();
            EnterpriseWastewaterChartVO.CategoryOptionVO enterpriseWastewater = 
                new EnterpriseWastewaterChartVO.CategoryOptionVO();
            enterpriseWastewater.setName("企业废水");
            enterpriseWastewater.setValue("enterprise");
            enterpriseWastewater.setSelected(true);
            mainCategories.add(enterpriseWastewater);
            
            // 默认废水类型
            List<EnterpriseWastewaterChartVO.TypeOptionVO> wastewaterTypes = new ArrayList<>();
            EnterpriseWastewaterChartVO.TypeOptionVO chromiumType = 
                new EnterpriseWastewaterChartVO.TypeOptionVO();
            chromiumType.setName("含铬废水");
            chromiumType.setValue("type_0");
            chromiumType.setSelected(true);
            wastewaterTypes.add(chromiumType);
            
            typeConfig.setMainCategories(mainCategories);
            typeConfig.setWastewaterTypes(wastewaterTypes);
            
            // 默认图表数据
            EnterpriseWastewaterChartVO.PollutantChartDataVO chartData = 
                new EnterpriseWastewaterChartVO.PollutantChartDataVO();
            chartData.setTimeLabels(Arrays.asList("09-01", "09-06", "09-12", "09-18"));

            List<EnterpriseWastewaterChartVO.PollutantSeriesVO> pollutantSeries = new ArrayList<>();
            
            // 默认六价铬数据
            EnterpriseWastewaterChartVO.PollutantSeriesVO hexavalentChromium = 
                new EnterpriseWastewaterChartVO.PollutantSeriesVO();
            hexavalentChromium.setName("六价铬");
            hexavalentChromium.setColor("#1890ff");
            hexavalentChromium.setIcon("●");
            hexavalentChromium.setData(Arrays.asList(BigDecimal.valueOf(40.0), BigDecimal.valueOf(65.0), 
                    BigDecimal.valueOf(30.0), BigDecimal.valueOf(35.0)));
            
            // 默认总镍数据
            EnterpriseWastewaterChartVO.PollutantSeriesVO totalNickel = 
                new EnterpriseWastewaterChartVO.PollutantSeriesVO();
            totalNickel.setName("总镍");
            totalNickel.setColor("#faad14");
            totalNickel.setIcon("●");
            totalNickel.setData(Arrays.asList(BigDecimal.valueOf(45.0), BigDecimal.valueOf(60.0), 
                    BigDecimal.valueOf(30.0), BigDecimal.valueOf(10.0)));
            
            // 默认总铬数据
            EnterpriseWastewaterChartVO.PollutantSeriesVO totalChromium = 
                new EnterpriseWastewaterChartVO.PollutantSeriesVO();
            totalChromium.setName("总铬");
            totalChromium.setColor("#f5222d");
            totalChromium.setIcon("●");
            totalChromium.setData(Arrays.asList(BigDecimal.valueOf(20.0), BigDecimal.valueOf(5.0), 
                    BigDecimal.valueOf(15.0), BigDecimal.valueOf(20.0)));
            
            pollutantSeries.add(hexavalentChromium);
            pollutantSeries.add(totalNickel);
            pollutantSeries.add(totalChromium);
            
            chartData.setPollutantSeries(pollutantSeries);
            chartData.setYAxisUnit("mg/L");
            chartData.setYAxisMax(100);
            
            data.setTypeConfig(typeConfig);
            data.setChartData(chartData);
            data.setCurrentDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        return data;
    }

    @Override
    public List<SewageWarningVO> getEnterpriseWastewaterType(String companyId) {
        LambdaQueryWrapper<SewageWarningConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SewageWarningConfig::getCompanyId, companyId);
        List<SewageWarningConfig> warningConfigs = sewageWarningConfigService.list(queryWrapper);
        return warningConfigs.stream().map(i->{
            SewageWarningVO sewageWarningVO = new SewageWarningVO();
            BeanUtils.copyProperties(i, sewageWarningVO);
            sewageWarningVO.setWasteWaterTypeName(pubParamDictionaryService.getNameByModuleAndCode("FSLX",i.getWasteWaterType()));
            return sewageWarningVO;
        }).sorted(Comparator.comparing(SewageWarningVO::getWasteWaterType)).collect(Collectors.toList());
    }

    @Override
    public PreDischargeWastewaterChartVO getPreDischargeWastewaterChart(String waterType) {
        log.info("开始获取预排口废水折线图数据，废水类型：{}", waterType);
        
        PreDischargeWastewaterChartVO data = new PreDischargeWastewaterChartVO();
        
        try {
            // 构建预排口废水类型选择配置
            PreDischargeWastewaterChartVO.PreDischargeTypeConfigVO typeConfig = 
                new PreDischargeWastewaterChartVO.PreDischargeTypeConfigVO();
            
            // 主要分类选项
            List<PreDischargeWastewaterChartVO.CategoryOptionVO> mainCategories = new ArrayList<>();
            
            PreDischargeWastewaterChartVO.CategoryOptionVO enterpriseWastewater = 
                new PreDischargeWastewaterChartVO.CategoryOptionVO();
            enterpriseWastewater.setName("企业废水");
            enterpriseWastewater.setValue("enterprise");
            enterpriseWastewater.setSelected(false);
            
            PreDischargeWastewaterChartVO.CategoryOptionVO preDischarge = 
                new PreDischargeWastewaterChartVO.CategoryOptionVO();
            preDischarge.setName("预排口");
            preDischarge.setValue("pre_discharge");
            preDischarge.setSelected(true); // 默认选中预排口
            
            mainCategories.add(enterpriseWastewater);
            mainCategories.add(preDischarge);
            
            // 具体预排口废水类型选项
            List<PreDischargeWastewaterChartVO.TypeOptionVO> wastewaterTypes = new ArrayList<>();
            
            String[] typeNames = {"含铬沉淀出水", "含镍沉淀出水", "综合沉淀出水"};
            String[] typeIds = {"1", "2", "3"};
            
            for (int i = 0; i < typeNames.length; i++) {
                PreDischargeWastewaterChartVO.TypeOptionVO typeOption = 
                    new PreDischargeWastewaterChartVO.TypeOptionVO();
                typeOption.setName(typeNames[i]);
                typeOption.setValue("type_" + i);
                typeOption.setId(typeIds[i]);
                typeOption.setSelected(i == 0); // 默认选中含铬沉淀出水
                wastewaterTypes.add(typeOption);
            }
            
            typeConfig.setMainCategories(mainCategories);
            typeConfig.setWastewaterTypes(wastewaterTypes);
            
            // 构建污染物浓度趋势图表数据
            PreDischargeWastewaterChartVO.PollutantChartDataVO chartData = 
                new PreDischargeWastewaterChartVO.PollutantChartDataVO();
            
            // 构建时间轴标签（最近18天，模拟图片中的时间范围）
            List<String> timeLabels = new ArrayList<>();
            LocalDateTime startDate = LocalDateTime.now().minusDays(17);
            for (int i = 0; i < 18; i++) {
                LocalDateTime date = startDate.plusDays(i);
                timeLabels.add(date.format(DateTimeFormatter.ofPattern("MM-dd")));
            }
            
            // 构建污染物数据系列
            List<PreDischargeWastewaterChartVO.PollutantSeriesVO> pollutantSeries = new ArrayList<>();
            
            // 根据废水类型生成不同的污染物数据
            if ("1".equals(waterType) || "type_0".equals(waterType)) {
                // 含铬沉淀出水 - 主要监测铬相关指标
                addChromiumPollutants(pollutantSeries);
            } else if ("2".equals(waterType) || "type_1".equals(waterType)) {
                // 含镍沉淀出水 - 主要监测镍相关指标
                addNickelPollutants(pollutantSeries);
            } else if ("3".equals(waterType) || "type_2".equals(waterType)) {
                // 综合沉淀出水 - 监测综合指标
                addComprehensivePollutants(pollutantSeries);
            } else {
                // 默认含铬沉淀出水
                addChromiumPollutants(pollutantSeries);
            }
            
            chartData.setTimeLabels(timeLabels);
            chartData.setPollutantSeries(pollutantSeries);
            chartData.setYAxisUnit("mg/L");
            chartData.setYAxisMax(100);
            
            data.setTypeConfig(typeConfig);
            data.setChartData(chartData);
            data.setCurrentDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            log.info("成功获取预排口废水折线图数据，废水类型：{}，包含{}个污染物指标，时间范围：{} 到 {}", 
                    waterType, pollutantSeries.size(), timeLabels.get(0), timeLabels.get(timeLabels.size() - 1));
            
        } catch (Exception e) {
            log.error("获取预排口废水折线图数据失败", e);
            // 返回默认数据
            data = createDefaultPreDischargeData();
        }
        
        return data;
    }

    @Override
    public List<PreDischargeWastewaterChartVO.TypeOptionVO> getPreDischargeWastewaterType() {
        log.info("开始获取预排口废水类型列表");
        
        List<PreDischargeWastewaterChartVO.TypeOptionVO> typeList = new ArrayList<>();
        
        String[] typeNames = {"含铬沉淀出水", "含镍沉淀出水", "综合沉淀出水"};
        String[] typeIds = {"1", "2", "3"};
        
        for (int i = 0; i < typeNames.length; i++) {
            PreDischargeWastewaterChartVO.TypeOptionVO typeOption = 
                new PreDischargeWastewaterChartVO.TypeOptionVO();
            typeOption.setName(typeNames[i]);
            typeOption.setValue("type_" + i);
            typeOption.setId(typeIds[i]);
            typeOption.setSelected(i == 0); // 默认选中第一个
            typeList.add(typeOption);
        }
        
        log.info("成功获取预排口废水类型列表，共{}种类型", typeList.size());
        return typeList;
    }

    @Override
    public EnterpriseWastewaterChartVO getEnterpriseWastewaterChartForHomeData(Object o) {
        return null;
    }

    @Override
    public RainfallOutletChartVO getRainfallOutletChartForHomePage() {
        log.info("开始获取雨排口折线图数据");

        RainfallOutletChartVO data = new RainfallOutletChartVO();

        try {
            // 获取最近5天的雨排口监控数据
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusDays(5);

            LambdaQueryWrapper<RainfallOutletMonitoring> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.between(RainfallOutletMonitoring::getMonitoringTime, startTime, endTime);
            queryWrapper.orderByAsc(RainfallOutletMonitoring::getMonitoringTime);

            List<RainfallOutletMonitoring> monitoringDataList = rainfallOutletMonitoringService.list(queryWrapper);

            // 构建闸阀状态信息
            RainfallOutletChartVO.ValveStatusVO valveStatus = new RainfallOutletChartVO.ValveStatusVO();
            if (!monitoringDataList.isEmpty()) {
                // 获取最新的闸阀状态
                RainfallOutletMonitoring latestData = monitoringDataList.get(monitoringDataList.size() - 1);
                String valveStatusValue = latestData.getRainOutletValveStatus();

                valveStatus.setStatus("开".equals(valveStatusValue) ? "开" : "关");
                valveStatus.setStatusColor("开".equals(valveStatusValue) ? "green" : "red");
                valveStatus.setValveType("手自一体闸阀");
            } else {
                // 默认状态
                valveStatus.setStatus("开");
                valveStatus.setStatusColor("green");
                valveStatus.setValveType("手自一体闸阀");
            }

            // 构建图表数据
            RainfallOutletChartVO.ChartDataVO chartData = new RainfallOutletChartVO.ChartDataVO();

            // 按日期分组数据，每天取平均值
            Map<String, List<RainfallOutletMonitoring>> dailyGroups = monitoringDataList.stream()
                    .collect(Collectors.groupingBy(monitoring ->
                            monitoring.getMonitoringTime().toLocalDate().toString()));

            // 构建时间轴标签（最近5天）
            List<String> timeLabels = new ArrayList<>();
            for (int i = 4; i >= 0; i--) {
                String date = LocalDateTime.now().minusDays(i).toLocalDate().toString();
                timeLabels.add(date);
            }

            // 构建PH值数据系列
            RainfallOutletChartVO.DataSeriesVO phSeries = new RainfallOutletChartVO.DataSeriesVO();
            phSeries.setName("降雨量");
            phSeries.setUnit("%");
            phSeries.setColor("#1890ff");
            phSeries.setIcon("◎");

            List<BigDecimal> phData = new ArrayList<>();
            for (String date : timeLabels) {
                List<RainfallOutletMonitoring> dayData = dailyGroups.get(date);
                if (dayData != null && !dayData.isEmpty()) {
                    // 计算当天PH值的平均值，保留2位小数
                    double avgPh = dayData.stream()
                            .filter(d -> d.getPhValue() != null)
                            .mapToDouble(d -> d.getPhValue().doubleValue())
                            .average()
                            .orElse(0.0);
                    phData.add(BigDecimal.valueOf(avgPh).setScale(2, RoundingMode.HALF_UP));
                } else {
                    // 生成模拟数据（40-60%之间波动），保留2位小数
                    double simulatedValue = 40 + Math.random() * 20;
                    phData.add(BigDecimal.valueOf(simulatedValue).setScale(2, RoundingMode.HALF_UP));
                }
            }
            phSeries.setData(phData);

            // 构建电导率数据系列
            RainfallOutletChartVO.DataSeriesVO conductivitySeries = new RainfallOutletChartVO.DataSeriesVO();
            conductivitySeries.setName("电导率");
            conductivitySeries.setUnit("μS/cm");
            conductivitySeries.setColor("#faad14");
            conductivitySeries.setIcon("●");

            List<BigDecimal> conductivityData = new ArrayList<>();
            for (String date : timeLabels) {
                List<RainfallOutletMonitoring> dayData = dailyGroups.get(date);
                if (dayData != null && !dayData.isEmpty()) {
                    // 计算当天电导率的平均值，保留2位小数
                    double avgConductivity = dayData.stream()
                            .filter(d -> d.getConductivity() != null)
                            .mapToDouble(d -> d.getConductivity().doubleValue())
                            .average()
                            .orElse(0.0);
                    conductivityData.add(BigDecimal.valueOf(avgConductivity).setScale(2, RoundingMode.HALF_UP));
                } else {
                    // 生成模拟数据（2000-3000μS/cm之间波动），保留2位小数
                    double simulatedValue = 2000 + Math.random() * 1000;
                    conductivityData.add(BigDecimal.valueOf(simulatedValue).setScale(2, RoundingMode.HALF_UP));
                }
            }
            conductivitySeries.setData(conductivityData);

            chartData.setTimeLabels(timeLabels);
            chartData.setPhSeries(phSeries);
            chartData.setConductivitySeries(conductivitySeries);

            data.setValveStatus(valveStatus);
            data.setChartData(chartData);
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            log.info("成功获取雨排口折线图数据，共{}条记录，时间范围：{} 到 {}",
                    monitoringDataList.size(), startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                    endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        } catch (Exception e) {
            log.error("获取雨排口折线图数据失败", e);
            // 返回默认数据
            RainfallOutletChartVO.ValveStatusVO valveStatus = new RainfallOutletChartVO.ValveStatusVO();
            valveStatus.setStatus("开");
            valveStatus.setStatusColor("green");
            valveStatus.setValveType("手自一体闸阀");

            RainfallOutletChartVO.ChartDataVO chartData = new RainfallOutletChartVO.ChartDataVO();

            // 生成最近5天的模拟时间标签
            List<String> timeLabels = new ArrayList<>();
            for (int i = 4; i >= 0; i--) {
                String date = LocalDateTime.now().minusDays(i).toLocalDate().toString();
                timeLabels.add(date);
            }

            // 生成模拟PH数据，保留2位小数
            RainfallOutletChartVO.DataSeriesVO phSeries = new RainfallOutletChartVO.DataSeriesVO();
            phSeries.setName("PH值");
            phSeries.setUnit("%");
            phSeries.setColor("#1890ff");
            phSeries.setIcon("◎");
            List<BigDecimal> phData = Arrays.asList(
                    BigDecimal.valueOf(45.00), BigDecimal.valueOf(52.00),
                    BigDecimal.valueOf(38.00), BigDecimal.valueOf(58.00), BigDecimal.valueOf(48.00)
            );
            phSeries.setData(phData);

            // 生成模拟电导率数据，保留2位小数
            RainfallOutletChartVO.DataSeriesVO conductivitySeries = new RainfallOutletChartVO.DataSeriesVO();
            conductivitySeries.setName("电导率");
            conductivitySeries.setUnit("μS/cm");
            conductivitySeries.setColor("#faad14");
            conductivitySeries.setIcon("●");
            List<BigDecimal> conductivityData = Arrays.asList(
                    BigDecimal.valueOf(2500.00), BigDecimal.valueOf(2800.00),
                    BigDecimal.valueOf(2200.00), BigDecimal.valueOf(2900.00), BigDecimal.valueOf(2600.00)
            );
            conductivitySeries.setData(conductivityData);

            chartData.setTimeLabels(timeLabels);
            chartData.setPhSeries(phSeries);
            chartData.setConductivitySeries(conductivitySeries);

            data.setValveStatus(valveStatus);
            data.setChartData(chartData);
            data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        data.setMonitorUrl("www.baidu.com");
        return data;
    }

    @Override
    public List<EnterpriseDetailVO> getEnterpriseDetail(String companyId) {
//        return List.of();
        ComCompany company=comCompanyService.getById(companyId);
        if (company==null) {
            return Collections.emptyList();
        }
        List<EnterpriseDetailVO> result = new ArrayList<>();
        if (!"1".equals(company.getIsSewagePlant())) {
            List<RainfallOutletMonitoring> rainfallOutletMonitorings = rainfallOutletMonitoringService.list(new LambdaQueryWrapper<RainfallOutletMonitoring>()
                    .eq(RainfallOutletMonitoring::getCompanyId, companyId));
            List<WasteGasMonitoring> wasteGasMonitorings = wasteGasMonitoringService.list(new LambdaQueryWrapper<WasteGasMonitoring>()
                    .eq(WasteGasMonitoring::getCompanyId, companyId));
            if (!CollectionUtils.isEmpty(rainfallOutletMonitorings)) {
                for (RainfallOutletMonitoring rainfallOutletMonitoring : rainfallOutletMonitorings) {
                    EnterpriseDetailVO enterpriseDetailVO = new EnterpriseDetailVO();
                    if ("雨排口阀门".equals(rainfallOutletMonitoring.getDeviceName())) {
                        enterpriseDetailVO.setName("雨排口液位");
                        enterpriseDetailVO.setValue(rainfallOutletMonitoring.getRainOutletLevel() + "");
                        result.add(enterpriseDetailVO);
                        EnterpriseDetailVO enterpriseDetailVO1 = new EnterpriseDetailVO();
                        BeanUtils.copyProperties(rainfallOutletMonitoring, enterpriseDetailVO1);
                        enterpriseDetailVO1.setName("雨排口阀门");
                        enterpriseDetailVO1.setValue(rainfallOutletMonitoring.getRainOutletValveStatus() );
                        result.add(enterpriseDetailVO1);
                    }
                    if ("应急池阀门".equals(rainfallOutletMonitoring.getDeviceName())) {
                        enterpriseDetailVO.setName("应急池液位");
                        enterpriseDetailVO.setValue(rainfallOutletMonitoring.getEmergencyPoolLevel() + "");
                        result.add(enterpriseDetailVO);
                        EnterpriseDetailVO enterpriseDetailVO1 = new EnterpriseDetailVO();
                        BeanUtils.copyProperties(rainfallOutletMonitoring, enterpriseDetailVO1);
                        enterpriseDetailVO1.setName("应急池阀门");
                        enterpriseDetailVO1.setValue(rainfallOutletMonitoring.getEmergencyPoolValveStatus() );
                        result.add(enterpriseDetailVO1);
                    }
                }
            }

            if (!CollectionUtils.isEmpty(wasteGasMonitorings)) {
                for (WasteGasMonitoring wasteGasMonitoring : wasteGasMonitorings) {
                    EnterpriseDetailVO enterpriseDetailVO = new EnterpriseDetailVO();
                    enterpriseDetailVO.setName(wasteGasMonitoring.getDeviceName() + "(" + wasteGasMonitoring.getMonitoringFactor() + ")");
                    if ("ORP".equals(wasteGasMonitoring.getMonitoringFactor())) {
                        enterpriseDetailVO.setValue(wasteGasMonitoring.getOrpValue() + "");
                    }
                    if ("PH".equals(wasteGasMonitoring.getMonitoringFactor())) {
                        enterpriseDetailVO.setValue(wasteGasMonitoring.getPhValue() + "");
                    }
                    result.add(enterpriseDetailVO);
                }

            }
            return result;
        }else {
            LambdaQueryWrapper<EnterpriseOutfallValve> dataQuery = new LambdaQueryWrapper<>();
            dataQuery.eq(EnterpriseOutfallValve::getCompanyId, companyId)
                    .orderByDesc(EnterpriseOutfallValve::getMonitoringTime)
                    .last("LIMIT 1");
            EnterpriseOutfallValve latestData = enterpriseOutfallValveService.getOne(dataQuery,false);
            if (latestData != null) {
                EnterpriseDetailVO cod = new EnterpriseDetailVO();
                cod.setName("COD(mg/L)");
                cod.setValue(latestData.getCodAvg()+"");
                result.add(cod);
                EnterpriseDetailVO ammoniaNitrogenAvg = new EnterpriseDetailVO();
                ammoniaNitrogenAvg.setName("氨氮(mg/L)");
                ammoniaNitrogenAvg.setValue(latestData.getAmmoniaNitrogenAvg()!=null?latestData.getAmmoniaNitrogenAvg()+"":"/");
                result.add(ammoniaNitrogenAvg);
                EnterpriseDetailVO totalPhosphorusAvg = new EnterpriseDetailVO();
                totalPhosphorusAvg.setName("总磷(mg/L)");
                totalPhosphorusAvg.setValue(latestData.getTotalPhosphorusAvg()!=null?latestData.getTotalPhosphorusAvg()+"":"/");
                result.add(totalPhosphorusAvg);
                EnterpriseDetailVO totalNitrogenAvg = new EnterpriseDetailVO();
                totalNitrogenAvg.setName("总氮(mg/L)");
                totalNitrogenAvg.setValue(latestData.getTotalNitrogenAvg()!=null?latestData.getTotalNitrogenAvg()+"":"/");
                result.add(totalNitrogenAvg);
                EnterpriseDetailVO totalCopperAvg = new EnterpriseDetailVO();
                totalCopperAvg.setName("总铜(mg/L)");
                totalCopperAvg.setValue(latestData.getTotalCopperAvg()!=null?latestData.getTotalCopperAvg()+"":"/");
                result.add(totalCopperAvg);
                EnterpriseDetailVO totalChromiumAvg = new EnterpriseDetailVO();
                totalChromiumAvg.setName("总铬(mg/L)");
                totalChromiumAvg.setValue(latestData.getTotalChromiumAvg()!=null?latestData.getTotalChromiumAvg()+"":"/");
                result.add(totalChromiumAvg);
                EnterpriseDetailVO totalZincAvg = new EnterpriseDetailVO();
                totalZincAvg.setName("总铬(mg/L)");
                totalZincAvg.setValue(latestData.getTotalZincAvg()!=null?latestData.getTotalZincAvg()+"":"/");
                result.add(totalZincAvg);
                EnterpriseDetailVO flowRateAvg = new EnterpriseDetailVO();
                flowRateAvg.setName("流量(m³/h)");
                flowRateAvg.setValue(latestData.getFlowRateAvg()!=null?latestData.getFlowRateAvg()+"":"/");
                result.add(flowRateAvg);
                EnterpriseDetailVO ph = new EnterpriseDetailVO();
                ph.setName("PH");
                ph.setValue(latestData.getPhAvg()!=null?latestData.getPhAvg()+"":"/");
                result.add(ph);
            }
            return result;
        }

    }

    /**
     * 添加铬相关污染物数据
     */
    private void addChromiumPollutants(List<PreDischargeWastewaterChartVO.PollutantSeriesVO> pollutantSeries) {
        // 六价铬数据系列（蓝色）
        PreDischargeWastewaterChartVO.PollutantSeriesVO hexavalentChromium =
                new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        hexavalentChromium.setName("六价铬");
        hexavalentChromium.setColor("#1890ff");
        hexavalentChromium.setIcon("●");

        // 生成六价铬的模拟数据（30-50mg/L之间波动）
        List<BigDecimal> chromiumData = Arrays.asList(
                BigDecimal.valueOf(35.0), BigDecimal.valueOf(40.0), BigDecimal.valueOf(45.0),
                BigDecimal.valueOf(50.0), BigDecimal.valueOf(42.0), BigDecimal.valueOf(38.0),
                BigDecimal.valueOf(35.0), BigDecimal.valueOf(40.0), BigDecimal.valueOf(45.0),
                BigDecimal.valueOf(48.0), BigDecimal.valueOf(46.0), BigDecimal.valueOf(42.0),
                BigDecimal.valueOf(38.0), BigDecimal.valueOf(35.0), BigDecimal.valueOf(40.0),
                BigDecimal.valueOf(45.0), BigDecimal.valueOf(42.0), BigDecimal.valueOf(38.0)
        );
        hexavalentChromium.setData(chromiumData);

        // 总铬数据系列（红色）
        PreDischargeWastewaterChartVO.PollutantSeriesVO totalChromium =
                new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        totalChromium.setName("总铬");
        totalChromium.setColor("#f5222d");
        totalChromium.setIcon("●");

        // 生成总铬的模拟数据（15-35mg/L之间波动）
        List<BigDecimal> totalChromiumData = Arrays.asList(
                BigDecimal.valueOf(20.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(30.0),
                BigDecimal.valueOf(35.0), BigDecimal.valueOf(28.0), BigDecimal.valueOf(22.0),
                BigDecimal.valueOf(18.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(30.0),
                BigDecimal.valueOf(32.0), BigDecimal.valueOf(28.0), BigDecimal.valueOf(24.0),
                BigDecimal.valueOf(20.0), BigDecimal.valueOf(18.0), BigDecimal.valueOf(22.0),
                BigDecimal.valueOf(28.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(20.0)
        );
        totalChromium.setData(totalChromiumData);

        // 总铬数据系列（红色）
        PreDischargeWastewaterChartVO.PollutantSeriesVO totalTemp =
                new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        totalTemp.setName("总镍");
        totalTemp.setColor("#f5222d");
        totalTemp.setIcon("●");

        // 生成总铬的模拟数据（15-35mg/L之间波动）
        List<BigDecimal> totalTempData = Arrays.asList(
                BigDecimal.valueOf(21.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(30.0),
                BigDecimal.valueOf(32.0), BigDecimal.valueOf(28.0), BigDecimal.valueOf(22.0),
                BigDecimal.valueOf(28.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(30.0),
                BigDecimal.valueOf(32.0), BigDecimal.valueOf(28.0), BigDecimal.valueOf(24.0),
                BigDecimal.valueOf(21.0), BigDecimal.valueOf(18.0), BigDecimal.valueOf(22.0),
                BigDecimal.valueOf(23.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(20.0)
        );
        totalTemp.setData(totalTempData);

        pollutantSeries.add(totalTemp);
        pollutantSeries.add(hexavalentChromium);
        pollutantSeries.add(totalChromium);
    }

    /**
     * 添加镍相关污染物数据
     */
    private void addNickelPollutants(List<PreDischargeWastewaterChartVO.PollutantSeriesVO> pollutantSeries) {
        // 总镍数据系列（黄色）
        PreDischargeWastewaterChartVO.PollutantSeriesVO hexavalentChromium =
                new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        hexavalentChromium.setName("六价铬");
        hexavalentChromium.setColor("#1890ff");
        hexavalentChromium.setIcon("●");

        // 生成六价铬的模拟数据（30-50mg/L之间波动）
        List<BigDecimal> chromiumData = Arrays.asList(
                BigDecimal.valueOf(35.0), BigDecimal.valueOf(40.0), BigDecimal.valueOf(45.0),
                BigDecimal.valueOf(50.0), BigDecimal.valueOf(42.0), BigDecimal.valueOf(38.0),
                BigDecimal.valueOf(35.0), BigDecimal.valueOf(40.0), BigDecimal.valueOf(45.0),
                BigDecimal.valueOf(48.0), BigDecimal.valueOf(46.0), BigDecimal.valueOf(42.0),
                BigDecimal.valueOf(38.0), BigDecimal.valueOf(35.0), BigDecimal.valueOf(40.0),
                BigDecimal.valueOf(45.0), BigDecimal.valueOf(42.0), BigDecimal.valueOf(38.0)
        );
        hexavalentChromium.setData(chromiumData);

        // 总铬数据系列（红色）
        PreDischargeWastewaterChartVO.PollutantSeriesVO totalChromium =
                new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        totalChromium.setName("总铬");
        totalChromium.setColor("#f5222d");
        totalChromium.setIcon("●");

        // 生成总铬的模拟数据（15-35mg/L之间波动）
        List<BigDecimal> totalChromiumData = Arrays.asList(
                BigDecimal.valueOf(20.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(30.0),
                BigDecimal.valueOf(35.0), BigDecimal.valueOf(28.0), BigDecimal.valueOf(22.0),
                BigDecimal.valueOf(18.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(30.0),
                BigDecimal.valueOf(32.0), BigDecimal.valueOf(28.0), BigDecimal.valueOf(24.0),
                BigDecimal.valueOf(20.0), BigDecimal.valueOf(18.0), BigDecimal.valueOf(22.0),
                BigDecimal.valueOf(28.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(20.0)
        );
        totalChromium.setData(totalChromiumData);

        // 总铬数据系列（红色）
        PreDischargeWastewaterChartVO.PollutantSeriesVO totalTemp =
                new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        totalTemp.setName("总镍");
        totalTemp.setColor("#f5222d");
        totalTemp.setIcon("●");

        // 生成总铬的模拟数据（15-35mg/L之间波动）
        List<BigDecimal> totalTempData = Arrays.asList(
                BigDecimal.valueOf(21.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(30.0),
                BigDecimal.valueOf(32.0), BigDecimal.valueOf(28.0), BigDecimal.valueOf(22.0),
                BigDecimal.valueOf(28.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(30.0),
                BigDecimal.valueOf(32.0), BigDecimal.valueOf(28.0), BigDecimal.valueOf(24.0),
                BigDecimal.valueOf(21.0), BigDecimal.valueOf(18.0), BigDecimal.valueOf(22.0),
                BigDecimal.valueOf(23.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(20.0)
        );
        totalTemp.setData(totalTempData);

        pollutantSeries.add(totalTemp);
        pollutantSeries.add(hexavalentChromium);
        pollutantSeries.add(totalChromium);
    }

    /**
     * 添加综合污染物数据
     */
    private void addComprehensivePollutants(List<PreDischargeWastewaterChartVO.PollutantSeriesVO> pollutantSeries) {
        // 总铬数据系列（红色）
        PreDischargeWastewaterChartVO.PollutantSeriesVO totalChromium = 
            new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        totalChromium.setName("总铬");
        totalChromium.setColor("#f5222d");
        totalChromium.setIcon("●");
        
        // 生成总铬的模拟数据（8-25mg/L之间波动）
        List<BigDecimal> totalChromiumData = Arrays.asList(
            BigDecimal.valueOf(12.0), BigDecimal.valueOf(15.0), BigDecimal.valueOf(18.0),
            BigDecimal.valueOf(22.0), BigDecimal.valueOf(25.0), BigDecimal.valueOf(20.0),
            BigDecimal.valueOf(16.0), BigDecimal.valueOf(14.0), BigDecimal.valueOf(18.0),
            BigDecimal.valueOf(22.0), BigDecimal.valueOf(20.0), BigDecimal.valueOf(16.0),
            BigDecimal.valueOf(12.0), BigDecimal.valueOf(10.0), BigDecimal.valueOf(14.0),
            BigDecimal.valueOf(18.0), BigDecimal.valueOf(15.0), BigDecimal.valueOf(12.0)
        );
        totalChromium.setData(totalChromiumData);
        
        // 总镍数据系列（黄色）
        PreDischargeWastewaterChartVO.PollutantSeriesVO totalNickel = 
            new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        totalNickel.setName("总镍");
        totalNickel.setColor("#faad14");
        totalNickel.setIcon("●");
        
        // 生成总镍的模拟数据（5-20mg/L之间波动）
        List<BigDecimal> nickelData = Arrays.asList(
            BigDecimal.valueOf(8.0), BigDecimal.valueOf(10.0), BigDecimal.valueOf(12.0),
            BigDecimal.valueOf(15.0), BigDecimal.valueOf(18.0), BigDecimal.valueOf(20.0),
            BigDecimal.valueOf(16.0), BigDecimal.valueOf(12.0), BigDecimal.valueOf(10.0),
            BigDecimal.valueOf(14.0), BigDecimal.valueOf(18.0), BigDecimal.valueOf(16.0),
            BigDecimal.valueOf(12.0), BigDecimal.valueOf(8.0), BigDecimal.valueOf(10.0),
            BigDecimal.valueOf(14.0), BigDecimal.valueOf(12.0), BigDecimal.valueOf(8.0)
        );
        totalNickel.setData(nickelData);
        
        // 总铜数据系列（蓝色）
        PreDischargeWastewaterChartVO.PollutantSeriesVO totalCopper = 
            new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        totalCopper.setName("总铜");
        totalCopper.setColor("#1890ff");
        totalCopper.setIcon("●");
        
        // 生成总铜的模拟数据（3-15mg/L之间波动）
        List<BigDecimal> copperData = Arrays.asList(
            BigDecimal.valueOf(5.0), BigDecimal.valueOf(8.0), BigDecimal.valueOf(10.0),
            BigDecimal.valueOf(12.0), BigDecimal.valueOf(15.0), BigDecimal.valueOf(12.0),
            BigDecimal.valueOf(10.0), BigDecimal.valueOf(8.0), BigDecimal.valueOf(6.0),
            BigDecimal.valueOf(9.0), BigDecimal.valueOf(12.0), BigDecimal.valueOf(10.0),
            BigDecimal.valueOf(8.0), BigDecimal.valueOf(5.0), BigDecimal.valueOf(7.0),
            BigDecimal.valueOf(10.0), BigDecimal.valueOf(8.0), BigDecimal.valueOf(6.0)
        );
        totalCopper.setData(copperData);
        
        pollutantSeries.add(totalChromium);
        pollutantSeries.add(totalNickel);
        pollutantSeries.add(totalCopper);
    }

    /**
     * 创建默认预排口数据
     */
    private PreDischargeWastewaterChartVO createDefaultPreDischargeData() {
        PreDischargeWastewaterChartVO data = new PreDischargeWastewaterChartVO();
        
        // 默认类型配置
        PreDischargeWastewaterChartVO.PreDischargeTypeConfigVO typeConfig = 
            new PreDischargeWastewaterChartVO.PreDischargeTypeConfigVO();
        
        // 默认主要分类
        List<PreDischargeWastewaterChartVO.CategoryOptionVO> mainCategories = new ArrayList<>();
        PreDischargeWastewaterChartVO.CategoryOptionVO preDischarge = 
            new PreDischargeWastewaterChartVO.CategoryOptionVO();
        preDischarge.setName("预排口");
        preDischarge.setValue("pre_discharge");
        preDischarge.setSelected(true);
        mainCategories.add(preDischarge);
        
        // 默认废水类型
        List<PreDischargeWastewaterChartVO.TypeOptionVO> wastewaterTypes = new ArrayList<>();
        PreDischargeWastewaterChartVO.TypeOptionVO chromiumType = 
            new PreDischargeWastewaterChartVO.TypeOptionVO();
        chromiumType.setName("含铬沉淀出水");
        chromiumType.setValue("type_0");
        chromiumType.setId("1");
        chromiumType.setSelected(true);
        wastewaterTypes.add(chromiumType);
        
        typeConfig.setMainCategories(mainCategories);
        typeConfig.setWastewaterTypes(wastewaterTypes);
        
        // 默认图表数据
        PreDischargeWastewaterChartVO.PollutantChartDataVO chartData = 
            new PreDischargeWastewaterChartVO.PollutantChartDataVO();
        chartData.setTimeLabels(Arrays.asList("09-01", "09-06", "09-12", "09-18"));
        
        List<PreDischargeWastewaterChartVO.PollutantSeriesVO> pollutantSeries = new ArrayList<>();
        
        // 默认六价铬数据
        PreDischargeWastewaterChartVO.PollutantSeriesVO hexavalentChromium = 
            new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        hexavalentChromium.setName("六价铬");
        hexavalentChromium.setColor("#1890ff");
        hexavalentChromium.setIcon("●");
        hexavalentChromium.setData(Arrays.asList(BigDecimal.valueOf(35.0), BigDecimal.valueOf(45.0), 
                BigDecimal.valueOf(38.0), BigDecimal.valueOf(42.0)));
        
        // 默认总铬数据
        PreDischargeWastewaterChartVO.PollutantSeriesVO totalChromium = 
            new PreDischargeWastewaterChartVO.PollutantSeriesVO();
        totalChromium.setName("总铬");
        totalChromium.setColor("#f5222d");
        totalChromium.setIcon("●");
        totalChromium.setData(Arrays.asList(BigDecimal.valueOf(20.0), BigDecimal.valueOf(30.0), 
                BigDecimal.valueOf(22.0), BigDecimal.valueOf(25.0)));
        
        pollutantSeries.add(hexavalentChromium);
        pollutantSeries.add(totalChromium);
        
        chartData.setPollutantSeries(pollutantSeries);
        chartData.setYAxisUnit("mg/L");
        chartData.setYAxisMax(100);
        
        data.setTypeConfig(typeConfig);
        data.setChartData(chartData);
        data.setCurrentDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }
}
